﻿#include"XQRunnable.h"
#include"XQTaskPool.h"
#include<QEventLoop>
#include<QCoreApplication>
#include<QThread>
XQRunnable::XQRunnable()
{
	
}

XQRunnable::~XQRunnable()
{

}

XQRunnable* XQRunnable::create(std::function<void(XQRunnable*)> functionToRun)
{
	auto Runnable = new XQRunnable();
	Runnable->setFunc(functionToRun);
	return Runnable;
}
XQRunnable* XQRunnable::create(std::function<void()> functionToRun)
{
	return create([=](XQRunnable*) {functionToRun(); });
}
XQTaskPool* XQRunnable::taskPool() const
{
	return m_taskPool;
}
bool XQRunnable::isInterruptionRequested()
{
	return m_stop;
}

bool XQRunnable::isQuit()
{
	return m_quit;
}

void XQRunnable::requestInterruption()
{
	m_stop = true;
}

void XQRunnable::wait_event()
{
	while (!m_quit)
	{
		QCoreApplication::processEvents(QEventLoop::AllEvents);
	}
}

void XQRunnable::wait(int msec)
{
	while (!m_quit)
		QThread::msleep(msec) ;
}

void XQRunnable::run()
{
	if (m_taskPool != nullptr)
		m_taskPool->runTask(this);
	if(!isInterruptionRequested())
		m_func(this);//执行任务
	m_quit = true;//任务退出的标记
	if (m_taskPool != nullptr)
		m_taskPool->freeTask(this);
}

void XQRunnable::setFunc(std::function<void(XQRunnable*)> functionToRun)
{
	m_func = functionToRun;
}

void XQRunnable::setTaskPool(XQTaskPool* taskPool)
{
	m_taskPool = taskPool;
}